package com.wunong.smart.collection.domain.state.impl;

import com.wunong.smart.collection.domain.model.CollectionDomain;
import com.wunong.smart.collection.domain.state.CollectionState;
import com.wunong.smart.collection.domain.state.CollectionStateFactory;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author create by zealot.zt
 */
public class DefaultCollectionStateFactory implements CollectionStateFactory, ApplicationContextAware {

    private final Map<Integer, CollectionState> stateMap = new ConcurrentHashMap<>();

    @Override
    public CollectionState getState(CollectionDomain domain) {
        Integer status = domain.getStatusEnum().getCode();
        return getState(status);
    }

    @Override
    public CollectionState getState(Integer status) {
        if (status == null) {
            return null;
        }

        return stateMap.get(status);
    }

    @Override
    public void register(CollectionState state) {
        stateMap.put(state.getStatus(), state);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, CollectionState> map = applicationContext.getBeansOfType(CollectionState.class);
        if (MapUtils.isNotEmpty(map)) {
            map.forEach((k, v) -> this.register(v));
        }
    }

}
